using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Domain.MainModule.Entities;
using Application.MainModule.DinnerManagement;
using Presentation.Web.UI.Attibutes;
using Presentation.Web.ViewModels;
using Presentation.Web.Core.Geolocation;
using Presentation.Web.Core.Pagination;

namespace Presentation.Web.UI.Controllers
{
    [HandleErrorWithELMAH]
    public class SearchController : Controller
    {
        readonly IDinnerManagementService _dinnerService;
        //
        // Dependency Injection enabled constructors

        public SearchController(IDinnerManagementService dinnerService)
        {
            _dinnerService = dinnerService;
        }

        //
        // AJAX: /Search/FindByLocation?longitude=45&latitude=-90

        [HttpPost]
        public ActionResult SearchByLocation(float latitude, float longitude)
        {

            var dinners = _dinnerService.FindByLocation(latitude, longitude);

            var jsonDinners = from dinner in dinners
                              select JsonDinnerFromDinner(dinner);

            return Json(jsonDinners.ToList());
        }

        [HttpPost]
        public ActionResult SearchByPlaceNameOrZip(string Location)
        {
            if (String.IsNullOrEmpty(Location)) return null; ;
            LatLong location = GeolocationService.PlaceOrZipToLatLong(Location);
            if (location != null)
            {
                var dinners = _dinnerService.
                                FindByLocation(location.Lat, location.Long).
                                OrderByDescending(p => p.EventDate);

                return View("Results", dinners.AsPagination(1, 20));
            }
            return View("Results", null);
        }

        //
        // AJAX: /Search/GetMostPopularDinners
        // AJAX: /Search/GetMostPopularDinners?limit=5

        [HttpPost]
        public ActionResult GetMostPopularDinners(int? limit = 40)
        {
            var mostPopularDinners = _dinnerService.GetMostPopularDinners(limit.Value);

            var jsonDinners = mostPopularDinners.Select(JsonDinnerFromDinner);
            return Json(jsonDinners.ToList());
        }

        private JsonDinner JsonDinnerFromDinner(Dinners dinner)
        {
            return new JsonDinner
            {
                DinnerID = dinner.DinnerID,
                EventDate = dinner.EventDate,
                Latitude = dinner.Latitude,
                Longitude = dinner.Longitude,
                Title = dinner.Title,
                Description = dinner.Description,
                RSVPCount = dinner.RSVPs.Count,
                Url = dinner.DinnerID.ToString(CultureInfo.InvariantCulture)
            };
        }

    }
}